﻿using System;
using System.Security.Policy;
using System.Windows;

using boda.net.wpf.core.Enums;
using boda.net.wpf.core.Helper;
using boda.net.wpf.core.Ioc;

namespace boda.net.wpf.core.Languages;
[ExposedService(false, LifeTime.Singleton, typeof(ILanguageManager))]
public class LanguageManager : ILanguageManager
{
    private ResourceDictionary Resource { get; set; }

    private string _url = string.Empty;

    public LanguageManager()
    {
        Set(LanguageType.CN);
    }

    /// <summary>
    /// 索引器
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public string this[string key]
    {
        get
        {
            if (Resource != null && Resource.Contains(key))
            {
                return Resource[key].ToString();
            }

            return this[key];
        }
    }

    public LanguageType Current { get; private set; }

    public void Set(LanguageType language)
    {
        Assert.NotNull(language);

        if (string.IsNullOrEmpty(this._url))
        {
            ResourceDictionary resourceDictionary = Application.Current.Resources.MergedDictionaries[0];
            string path = resourceDictionary.Source.AbsolutePath;
            this._url = path.Remove(path.LastIndexOf('/'));
        }

        string target = $"{_url}/{language}.xaml";
        this.Resource = (ResourceDictionary)Application.LoadComponent(new Uri(target, UriKind.RelativeOrAbsolute));
        Application.Current.Resources.MergedDictionaries.RemoveAt(0);
        Application.Current.Resources.MergedDictionaries.Insert(0, Resource);

        if (Current != language)
        {
            this.Current = language;

            // TODO 保存到系统设置里面
        }
    }
}
